//
//  VehicleDeatailsTopCell.swift
//  koolcar
//
//  Created by kuaimaxiansheng on 2023/10/17.
//

import UIKit
import Kingfisher
import JXPhotoBrowser
import FSPagerView
class VehicleDeatailsTopCell: UITableViewCell {
    var pagerView: FSPagerView!
    var pageControl: TYPageControl!
    var dataArray: [String] = []
    var appearanceImages: [String] = []//外观
    var interiorImages: [String] = []//内饰
    var engineChassisImages: [String] = []//底盘
    var logoImageView: UIImageView!
    var brandNameLab: UILabel!
    var nameLab: UILabel!
    var contentModel: CarDetailsContentModel!
    var seaCarFlag: Bool = false
    var orerFlag: Bool = false
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.selectionStyle = .none
        self.backgroundColor = .white
        self.clipsToBounds = true
        self.initUI()
    }
    
    func initUI(){
        // Create a pager view
        self.pagerView = FSPagerView(frame: CGRect(x: 0, y: 10, width: kScreenWidth, height: 280))
        self.pagerView.dataSource = self
        self.pagerView.delegate = self
        self.pagerView.decelerationDistance = 1
        let width = (kScreenWidth)
        self.pagerView.interitemSpacing = 10
        self.pagerView.isInfinite = false//顺时针一直滑动
        self.pagerView.itemSize = CGSize(width: width, height: 280)
        self.pagerView.register(CarShowImageCell.self, forCellWithReuseIdentifier: "CarShowImageCell")
        self.contentView.addSubview(self.pagerView)
        
        self.pageControl = TYPageControl(frame: CGRect(x: 0, y: self.pagerView.frame.maxY + 6, width: kScreenWidth, height: 4))
        self.pageControl.currentPageIndicatorSize = CGSize(width: 6, height: 6)
        self.pageControl.pageIndicatorSize = CGSize(width: 6, height: 6)
        self.pageControl.backgroundColor = UIColor.clear
        self.pageControl.currentPage = 0
        self.pageControl.currentPageIndicatorTintColor = Theme.mainColor
        self.pageControl.pageIndicatorTintColor = UIColor(hex: 0x005C99,alpha: 0.1)//不活跃指示器颜色
        self.pagerView.addSubview(self.pageControl)
        
        self.logoImageView = UIImageView(frame: .zero)
        self.logoImageView.layer.cornerRadius = 17
        self.logoImageView.clipsToBounds = true
        self.contentView.addSubview(self.logoImageView)
        
        self.brandNameLab = UILabel(frame: .zero)
        self.brandNameLab.textColor = Theme.titleLabColor
        self.brandNameLab.font = UIFont.init(name: Theme.PingFangSCMedium, size: 16)
        self.brandNameLab.textAlignment = .left
        self.contentView.addSubview(self.brandNameLab)
        
        self.nameLab = UILabel(frame: .zero)
        self.nameLab.textColor = Theme.titleLabColor
        self.nameLab.font = UIFont.init(name: Theme.PingFangSCMedium, size: 14)
        self.nameLab.textAlignment = .left
        self.nameLab.numberOfLines = 0
        self.contentView.addSubview(self.nameLab)
        
        self.addLayout()
    }
    
    
    private func addLayout(){
        self.pagerView.snp.makeConstraints { make in
            make.top.equalTo(0)
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.height.equalTo(280)
        }
        
        self.pageControl.snp.makeConstraints { make in
            make.centerX.equalTo(self.pageControl.snp.centerX)
            make.height.equalTo(10)
            make.left.equalTo(38)
            make.right.equalTo(-38)
            make.bottom.equalTo(-50)
        }
        
        self.logoImageView.snp.makeConstraints { make in
            make.top.equalTo(self.pagerView.snp.bottom).offset(14)
            make.left.equalTo(14)
            make.width.height.equalTo(34)
        }
        
        self.brandNameLab.snp.makeConstraints { make in
            make.left.equalTo(self.logoImageView.snp.right).offset(10)
            make.centerY.equalTo(self.logoImageView.snp.centerY)
            make.right.equalTo(-14)
        }
        
        self.nameLab.snp.makeConstraints { make in
            make.top.equalTo(self.logoImageView.snp.bottom).offset(14)
            make.left.equalTo(14)
            make.right.equalTo(-14)
            make.bottom.equalTo(-5)
        }
    }
    
    //Model
    func setContentModel(contentModel: CarDetailsContentModel){
        self.contentModel = contentModel
        //外观
        if (contentModel.appearanceImages ?? "") != ""{
            let appearArray = (contentModel.appearanceImages ?? "").components(separatedBy: ",")
            self.appearanceImages = appearArray
        }
        
        //内饰
        if (contentModel.interiorImages ?? "") != ""{
            let interiorIArray = (contentModel.interiorImages ?? "").components(separatedBy: ",")
            self.interiorImages = interiorIArray
        }
    
        //底盘
        if (contentModel.engineChassisImages ?? "") != ""{
            let  engineChassisArray = (contentModel.engineChassisImages ?? "").components(separatedBy: ",")
            self.engineChassisImages = engineChassisArray
        }
              
        self.dataArray = self.appearanceImages
        //logo
        if self.orerFlag == false, let logoUrl = URL.init(string: contentModel.logo ?? "") {
            self.logoImageView.sd_setImage(with: logoUrl)
            self.logoImageView.isHidden = false
            self.logoImageView.snp.updateConstraints { make in
                make.width.equalTo(34)
                make.left.equalTo(14)
            }
        }else{
            //预订不展示logo
            self.logoImageView.isHidden = true
            self.logoImageView.snp.updateConstraints { make in
                make.width.equalTo(0)
                make.left.equalTo(4)
            }
        }
        
        if self.seaCarFlag {
            //海外车
            self.brandNameLab.text = String(format: "%@-%@", contentModel.brandName ?? "", contentModel.name ?? "")
            
            let price = XTManageCenter.showPriceInComma(source: (contentModel.price ?? 0).cleanZero)
            self.nameLab.text = String(format: "%@%@", XTManageCenter.currentSign(), price)
            self.brandNameLab.font = UIFont.init(name: Theme.PingFangSCRegular, size: 16)
            self.nameLab.font = UIFont.init(name: Theme.PingFangSCMedium, size: 18)
            
            self.logoImageView.snp.makeConstraints { make in
                make.top.equalTo(self.pagerView.snp.bottom).offset(10)
            }
            self.nameLab.snp.makeConstraints { make in
                make.top.equalTo(self.logoImageView.snp.bottom).offset(6)
            }
        }else{
            //本地车
            self.brandNameLab.text = contentModel.brandName ?? ""
            self.nameLab.text = contentModel.name ?? ""
        }
       
        if contentModel.videoVrPdfList?.count == 0 {
            self.pageControl.snp.updateConstraints { make in
                make.bottom.equalTo(-10)
            }
        }

        self.pagerView.reloadData()
        self.updateConstraints()
    }
    
    
    //图片数组合并
    func getAllArray() -> NSMutableArray {
        let allArray = NSMutableArray()
        allArray.addObjects(from: self.appearanceImages)
//        allArray.addObjects(from: self.interiorImages)
        allArray.addObjects(from: self.engineChassisImages)
        allArray.insert(self.contentModel?.backgroundImage ?? "", at: 0)
        
        if allArray.count > 1 {
            self.pageControl.numberOfPages = allArray.count
        }else{
            self.pageControl.numberOfPages = 0
        }
        return allArray
    }
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        // Configure the view for the selected state
    }

}


extension VehicleDeatailsTopCell: FSPagerViewDataSource,FSPagerViewDelegate{
    
     func numberOfItems(in pagerView: FSPagerView) -> Int {
         let tempAll = self.getAllArray()
         return tempAll.count
    }
    
    func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
        let cell = pagerView.dequeueReusableCell(withReuseIdentifier: "CarShowImageCell", at: index) as! CarShowImageCell
        let tempAll = self.getAllArray()
        if tempAll.count > index, let str = tempAll[index] as? String, let url = URL.init(string: str) {
            cell.bgImgeView.sd_setImage(with: url, placeholderImage: UIImage(named: "icon_default_carS"))
        }
        if self.orerFlag {
            //预订页面不展示vr
            cell.bgVrView.isHidden = true
        }
        if self.contentModel != nil {
            cell.setContentModel(contentModel: self.contentModel)
        }
        
        return cell
    }
    
    func pagerView(_ pagerView: FSPagerView, didSelectItemAt index: Int) {
        pagerView.deselectItem(at: index, animated: true)
        pagerView.scrollToItem(at: index, animated: true)
        
        let tempAll = self.getAllArray()
        if tempAll.count > index{
            // 实例化
            let browser = JXPhotoBrowser()
            // 浏览过程中实时获取数据总量
            browser.numberOfItems = {tempAll.count}
            // 刷新Cell数据。本闭包将在Cell完成位置布局后调用。
            browser.reloadCellAtIndex = { context in
                let url = tempAll[context.index]
                let browserCell = context.cell as? JXPhotoBrowserImageCell
                browserCell?.index = context.index
                let collectionPath = IndexPath(item: context.index, section: 0)
                let collectionCell = pagerView.cellForItem(at: index) as? CarShowImageCell
                let placeholder = collectionCell?.bgImgeView.image
                // 用 SDWebImage 加载
                browserCell?.imageView.sd_setImage(with: URL.init(string: url as! String), placeholderImage: placeholder)
            }
            // UIPageIndicator样式的页码指示器
            browser.pageIndicator = JXPhotoBrowserNumberPageIndicator()
            browser.pageIndex = index
            browser.show()// 展示
        }
    }
    
 
    
    func pagerViewDidEndDecelerating(_ pagerView: FSPagerView){
        print("滑动到了第\(pagerView.currentIndex)个row")
        self.pageControl.currentPage = pagerView.currentIndex
    }
    
}
